package com.snail.interceptor;

//import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author Monica
 * @description
 * @date 2025/8/12 17:23
 */
public class GatewayTokenInterceptor implements HandlerInterceptor {

    // 从配置文件读取网关令牌（与网关保持一致）
    private final String gatewayToken;

    public GatewayTokenInterceptor(String gatewayToken) {
        this.gatewayToken = gatewayToken;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的网关令牌
        String token = request.getHeader("X-Gateway-Token");

        // 验证令牌是否存在且正确
        if (token == null || !token.equals(gatewayToken)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write("Access denied: Please access through gateway");
            return false;
        }
        // 验证令牌是否存在且正确
        return true;
    }
}